package com.fd.framework.core;

import com.fd.framework.core.entity.BaseResultCode;
import com.fd.framework.core.entity.Result;
import com.fd.framework.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * -业务异常处理
 * -运行时异常处理
 * 根据实际的需求, 进行叠加
 *
 * @author XiaoLong
 * @since 1.0.0
 */
@Slf4j
@ConditionalOnClass(HttpServletRequest.class)
@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(BizException.class)
    public Result<Void> handleException(BizException ex) {
        //记录日志
        log.error("[全局业务异常] 业务编码：{} 异常记录：{}", ex.getResultCode().getCode(), ex.getMessage(), ex);
        BaseResultCode resultCode = ex.getResultCode();
        return new Result<>(resultCode.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception ex) {
        //记录日志
        log.error("[系统运行时异常]", ex);
        return Result.fail(ex.getMessage());
    }
}
